package main.com.oaer.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import main.com.oaer.common.HibernateDaoUtil;
import main.com.oaer.dao.UserDao;
import main.com.oaer.model.PageList;
import main.com.oaer.model.User;
import main.com.oaer.util.CommonUtil;

@Repository
public class UserDaoImpl implements UserDao {

	@Autowired
	HibernateDaoUtil hibernateDaoUtil;
	
	@Override
	public void add(User user) {
		hibernateDaoUtil.save(user);
	}

	@Override
	public User load(Long id) {
		if(id==null) return null;
		return hibernateDaoUtil.load(User.class, id);
	}
	
	@Override
	public PageList findUsersByPage(Integer currentPage, Integer pageSize,User user){
		if(currentPage==null) return null;
		if(pageSize==null) return null;
		String hql="from User user where 1=1 ";
		List<Object> param = new ArrayList<Object>();
		if( CommonUtil.stringNotEmpty(user.getName()) ){
			hql +=" and user.name=?";
			param.add("'%"+user.getName()+"%'");
		}
		return hibernateDaoUtil.findListPageByHQL(hql, currentPage, pageSize, param.toArray());
	}

	@Override
	public void delete(User user) {
		if(user!=null){
			hibernateDaoUtil.delete(user);
		}
	}

	@Override
	public void update(User user) {
        if(user!=null){
    		hibernateDaoUtil.update(user);
        }
	}

	@Override
	public User findUserByUsername(String username) {
		if(username == null) return null;
		String hql = "from User user where user.name=?";
		return (User) hibernateDaoUtil.findEntityByHQL(hql, username);
	}

}
